import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:jiajia_diy/data/date_formate.dart';
import 'package:jiajia_diy/diyProject/diy.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:intl/intl.dart';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:image_picker/image_picker.dart';

/*
diy活动新增页面
 */
class DiyAdd extends StatefulWidget {
  DiyAdd({this.db, this.diyItems, this.diyItem});
  var db;
  List<Diy> diyItems;
  Diy diyItem;
  @override
  State<StatefulWidget> createState() => new DiyAddState();
}

class DiyAddState extends State<DiyAdd> {
  static var dateNow = DateTime.now();
  static var formatted = DateFormat('yyyy-MM-dd');
  String _dateTime = formatted.format(dateNow);
  int year = dateNow.year;
  int month = dateNow.month;
  int date = dateNow.day;

  String _imgPath = '';

  //获取照片地址
  Future _getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    String imgPath = image.path;
    setState(() {
      _imgPath = imgPath;
    });
  }

  //IOS风格的日期选择器
  void _showDatePicker(BuildContext context) {
    final bool showTitleActions = true;
    DatePicker.showDatePicker(
      context,
      showTitleActions: showTitleActions,
      minYear: 1970,
      maxYear: 2020,
      initialYear: year,
      initialMonth: month,
      initialDate: date,
      locale: 'zh',
      dateFormat: 'yyyy-mmm-dd',
      onConfirm: (year, month, date) {
        _settingDatetime(year, month, date);
      },
    );
  }

  //进行根据选择的日期进行日期设置
  void _settingDatetime(int year, int month, int date) {
    setState(() {
      this.year = year;
      this.month = month;
      this.date = date;
      _dateTime = '$year-$month-$date';
    });
  }

  //活动名称控制器
  TextEditingController _nameController = new TextEditingController();
  //活动地点控制器
  TextEditingController _placeController = new TextEditingController();
  //活动价格输入控制器
  TextEditingController _priceController = new TextEditingController();
  //活动联系人输入控制器
  TextEditingController _leaderController = new TextEditingController();
  //活动物料成本输入控制器
  TextEditingController _itemCostController = new TextEditingController();
  //活动人力成本输入控制器
  TextEditingController _laborCostController = new TextEditingController();

  //该页面的标题，跟随新增活动名称变化
  String _title = '';

  @override
  void initState() {
    super.initState();
    if (widget.diyItem != null) {
      _nameController.text = widget.diyItem.name;
      _placeController.text = widget.diyItem.place;
      _priceController.text = widget.diyItem.price.toString();
      _leaderController.text = widget.diyItem.leader;
      _itemCostController.text = widget.diyItem.itemCost.toString();
      _laborCostController.text = widget.diyItem.laborCost.toString();
      _imgPath = widget.diyItem.path;
    }
  }

  //为选取图片弹出对话框提示
  Widget _noImageDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text('请先选择活动照片后再保存'),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () => Navigator.of(context).pop(null),
              )
            ],
          );
        });
  }

  //先判断是新增还是更新，然后再进行数据库操作
  _saveHandleSubmitted(
      BuildContext context,
      String name,
      String place,
      String leader,
      String price,
      String itemCost,
      String laborCost,
      String profit,
      String imgPath) async {
    if (widget.diyItem == null) {
      Diy diy = new Diy(
          name,
          place,
          _dateTime,
          leader,
          int.parse(price),
          int.parse(itemCost),
          int.parse(laborCost),
          int.parse(profit),
          imgPath);
      int savedDiyId = await widget.db.saveDiy(diy);
      Diy addedDiyItem = await widget.db.getDiy(savedDiyId);
      widget.diyItems.insert(0, addedDiyItem);
    } else {
      Diy newDiyUpdata = Diy.fromMap({
        'name': _nameController.text,
        'place': _placeController.text,
        'date': _dateTime,
        'leader': _leaderController.text,
        'price': int.parse(price),
        'itemCost': int.parse(itemCost),
        'laborCost': int.parse(laborCost),
        'profit': int.parse(profit),
        'id': widget.diyItem.id
      });
      print('修改后的diy为：${newDiyUpdata.name}, ${newDiyUpdata.id}');
      int updatedDiyId = await widget.db.updateDiy(newDiyUpdata);
      print('updataeddId: $updatedDiyId');
      return newDiyUpdata;
    }
  }

  //根据输入的各项金额计算利润
  _profitCalculate() {
    int profit;
    profit = int.parse(
            _priceController.text == '' ? '0' : _priceController.text) -
        int.parse(
            _itemCostController.text == '' ? '0' : _itemCostController.text) -
        int.parse(
            _laborCostController.text == '' ? '0' : _laborCostController.text);
    return profit.toString();
  }

  //原生活动信息输入框
  Widget _inPutContainer(String text, TextInputType keyboardType,
      TextEditingController controller) {
    return new Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
      child: new TextField(
        keyboardType: keyboardType,
        autofocus: true,
        controller: controller,
        decoration: new InputDecoration(hintText: text, filled: true),
      ),
    );
  }

  //原生金额信息输入框
  Widget _inPutPriceContainer(String text, TextInputType keyboardType,
      TextEditingController controller) {
    return new Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
      child: new TextField(
        keyboardType: TextInputType.number,
        autofocus: true,
        controller: controller,
        decoration: new InputDecoration(
            border: OutlineInputBorder(),
            labelText: text,
            prefixText: '\￥',
            suffixText: 'CNY',
            suffixStyle: TextStyle(color: Colors.green)),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_title),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              if(_imgPath == ''){
                _noImageDialog(context);
              }else
              Navigator.pop(
                  context,
                  _saveHandleSubmitted(
                      context,
                      _nameController.text,
                      _placeController.text,
                      _leaderController.text,
                      _priceController.text == '' ? '0' : _priceController.text,
                      _itemCostController.text == ''
                          ? '0'
                          : _itemCostController.text,
                      _laborCostController.text == ''
                          ? '0'
                          : _laborCostController.text,
                      _profitCalculate(),
                      _imgPath));
            },
            child: new Text('保存',
                style: Theme.of(context)
                    .textTheme
                    .subhead
                    .copyWith(color: Colors.white)),
          )
        ],
      ),
      body: new ListView(
        children: <Widget>[
          new Column(
            children: <Widget>[
              new Padding(
                padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
                child: new InkWell(
                  onTap: () => _showDatePicker(context),
                  child: new Container(
                    child: new Row(
                      children: <Widget>[
                        new Icon(
                          Icons.today,
                          color: Theme.of(context).primaryColor,
                          size: 25.0,
                        ),
                        new Padding(
                          padding: const EdgeInsets.only(left: 10.0),
                          child: new Text(_dateTime),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              new Padding(
                padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
                child: new TextField(
                  autofocus: true,
                  // style: new TextStyle( height: .0, color: Colors.grey),
                  controller: _nameController,
                  decoration:
                      new InputDecoration(hintText: '活动名称', filled: true),
                  onChanged: (str) {
                    setState(() {
                      _title = str;
                    });
                  },
                ),
              ),
              _inPutContainer('活动地点', TextInputType.text, _placeController),
              _inPutContainer('联系人', TextInputType.text, _leaderController),
              _inPutPriceContainer(
                  '活动总价',
                  TextInputType.numberWithOptions(decimal: true, signed: true),
                  _priceController),
              new Row(
                children: <Widget>[
                  new Expanded(
                    child: _inPutPriceContainer(
                        '物料成本',
                        TextInputType.numberWithOptions(
                            decimal: true, signed: true),
                        _itemCostController),
                  ),
                  new Expanded(
                    child: _inPutPriceContainer(
                        '人力成本',
                        TextInputType.numberWithOptions(
                            decimal: true, signed: true),
                        _laborCostController),
                  )
                ],
              ),
              Container(
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0.0),
                child: _imgPath == ''
                    ? new FloatingActionButton(
                        child: new Icon(Icons.image),
                        onPressed: () {
                          _getImage();
                        },
                      )
                    : new SizedBox(
                        // height: 100.0,
                        // width: 300.0,
                        child: Image.file(
                          File(_imgPath),
                        ),
                      ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
